<template>
  <div v-if="loaded">
    <div style="margin:5px;" v-for="(rule, index) in rules[data.uri]" :key="index">
      <template
        v-if="
          rule.type == 'text' || $store.state.main.entry.sources[rule.source]
        "
      >
        {{ m(rule.caption) }}: {{ value(rule) }}
      </template>
    </div>
  </div>
</template>

<script>
import { m } from "@/store/yg/common/local";

export default {
  props: ["row", "data", "more"],
  data() {
    return {
      rules: {},
      loaded: false
    };
  },
  methods: {
    m(k) {
      return m(k);
    },
    loadOptions() {
      if (!this.rules[this.data.uri]) {
        return;
      }
      for (var i = 0; i < this.rules[this.data.uri].length; ++i) {
        var rule = this.rules[this.data.uri][i];
        this.$store.dispatch("loadOptionSource", rule.source);
      }
    },
    value(rule) {
      if (!this.data.displayRule) {
        return "";
      }
      var ruleMap = JSON.parse(this.data.displayRule);

      rule.options = this.$store.state.main.entry.sources[rule.source];
      if (rule.type == "select") {
        return this.source(ruleMap[rule.field], rule.options);
      } else if (rule.type == "multiselect") {
        if (!ruleMap[rule.field] || 0 == ruleMap[rule.field].length) {
          return "";
        }
        var result = "[ ";
        for (var i = 0; i < ruleMap[rule.field].length; ++i) {
          result += this.m(this.source(ruleMap[rule.field][i], rule.options));
          if (i < ruleMap[rule.field].length - 1) {
            result += ", ";
          }
        }
        result += " ]";

        return result;
      } else {
        return ruleMap[rule.field];
      }
    },
    source(value, options) {
      return options[value];
    }
  },
  created() {
    this.rules = JSON.parse(JSON.stringify(this.more));
    console.log(this.rules)

    if (!this.rules[this.data.uri]) {
      this.rules[this.data.uri] = [];
    }
    this.rules[this.data.uri].push({
      caption: "permission",
      field: "ROLE_ID",
      type: "multiselect",
      source: "roleSource"
    });

    this.loaded = true;
    this.loadOptions();
  }
};
</script>
